<template>
  <div>
    <!-- 布局容器 -->
    <el-container>
      <!-- 左侧菜单 -->
      <el-aside width="202px" style="background-color:#111A43;margin-left:20px;border:1px solid #60b6f1;" >
        <el-row class="tac">
          <!-- 导航菜单 -->
          <el-col>
            <el-menu :unique-opened="true"
             default-active="0"
              class="el-menu-vertical-demo"
              background-color="#111A43"
              text-color="#fff" 
              active-text-color="#0099FF">
              <el-submenu index="1">
                <template slot="title">
                  <span>区域</span>
                </template>
                <el-menu-item v-for="(item, num) in conlists" :key="item.id" class="el-icon-s-data" :index="String(num)"
                  @click="readinfo(item.code,item.onlineStatus)">{{ item.name }}</el-menu-item>
              </el-submenu>
            </el-menu>
          </el-col>
        </el-row>
      </el-aside>
      <!-- 中间内容 -->
      <!-- style="background-color: #0a1237;height: 100vh;" -->
      <el-main style="background-color:#0b1339;border:1px solid #60b6f1" >
        <div class="mainbox">
          <!-- 集控器控制 -->
          <div style="margin-bottom: 20px;">
            <span style="color: #fff;font-size:14px">集控器控制：</span>
            <!-- :disabled="this.conline ? false : true" -->
            <el-button size="mini" type="primary" @click="conallon">全开</el-button>
            <el-button size="mini" type="primary" @click="conalloff">全关</el-button>
            <!-- 定时开关 -->
            <span style="margin-left: 50px;color: #fff;font-size:14px">定时开关(左开右关)：</span>
            <el-time-picker
              style="width: 180px;"
              size="mini"
              v-model="value1"
              value-format="HH:mm:ss"
              placeholder="开灯时间">
            </el-time-picker>
            <el-time-picker
              style="width: 180px;"
              size="mini"
              v-model="value2"
              value-format="HH:mm:ss"
              placeholder="关灯时间">
            </el-time-picker>
            <el-button size="mini" type="primary" @click="setTime">确定</el-button>

          </div>
           <!-- 修改 -->
           <div v-if="resiveshow" style="font-size:14px;padding:60px;text-align:center;position:absolute;left:45%;top:30%;background:#fff;width:300px;height:150px;">
            <div>名称<el-input  maxlength="8" show-word-limit v-model="cabinetName" placeholder="请输入名称"></el-input></div>
            <div style="margin-top: 20px;">类型<el-input maxlength="2" show-word-limit v-model="cabinetType" placeholder="请输入类型"></el-input></div>
            <div style="margin-top: 20px;">
              <el-button @click="cancleshow()">取消</el-button>
              <el-button @click="revisename()" type="primary">确认</el-button></div>
          </div>

          <!-- 配电箱部分 -->  
          <div class="devrow" v-for="(dev, num) in devlist" :key="num" style="width:1350px;display:flex;flex-wrap: wrap;background-color:#0b1339;">

            <p style="color: #fff;width:1200px;height:20px;line-height:20px;text-align:center">{{ dev.cabinetCode }}</p>

            <div v-for="(item, num) in dev.deviceList" class="devbox" :key="num">
              <p style="color:#fff;height:20px;width:240px;text-align:center;margin-top: 2px">智能照明模块
                 <!-- <span style="margin-left: 15px;">状态：</span> -->
                 <i style="margin-left: 15px;" :class="item.status == 1 ? 'el-icon-success online' : 'el-icon-error notonline'"></i></p>
              <div
                style="width: 240px;height: 100px;margin-top:0px;font-size: 14px;background-color: #fff;border-radius:4px">
                <p style="font-size:12px;text-align:center;">编号：{{ item.code }} 名称：{{ item.cabinetName}}</p>

                <div style="margin-top:20px;margin-left:5px;width:230px;display: flex;align-items:baseline;flex-wrap: wrap;">

                  <div v-for="(item, num) in item.switchList" :key="num" style="margin-left:16px;flex-wrap:wrap;font-size:13px;display:flex;width: 10px;height:30px;text-align:left">
                    
                   
                    <div v-if="item.switchStatus" class="circle"
                      style="width:10px;height:10px; border-radius: 50%;background-color: greenyellow;">
                    </div>
                    <div v-else class="circle"
                      style="width:10px;height: 10px; border-radius: 50%;background-color: #999;">
                    </div>
                    <div style="width: 10px;">{{ item.loop }}</div>
                  </div>
                </div>

              </div> 

              <div style="margin-left: 40px;margin-top:8px">
                 <span @click="open(item.id)"  style="padding:2px;border-radius:2px;background-color: #1e90ff;color:#fff;cursor: pointer;font-size:14px">设备控制</span>
                  <span @click="revise(item.id)"  style="padding:2px;border-radius:2px;background-color: #b0e0e6;cursor: pointer;color:#fff;margin-left: 40px;font-size:14px">信息修改</span>
                  <!-- <span @click="addloop(item.id)"  style="padding:2px;border-radius:2px;background-color: #b0e044;cursor: pointer;color:#fff;margin-left: 20px;font-size:14px">添加回路</span> -->
              </div>
            </div>
          </div>

          <!-- <div v-for="(item,num) in devlist" class="devbox" :key="num" @click="open(item.id)">
            <span style="color: white;">编号：{{item.code}}</span>
            <div  style="width: 160px;height: 60px;margin-left: 35px;margin-top: 20px;display: flex;align-items:baseline;flex-wrap: wrap;font-size: 14px;background-color: white;border-radius: 4px;">

              <div v-for="(item,num) in item.switchList" :key="num" style="width: 20px;height:10px;text-align:left">
                <span>{{item.loop}}</span>
                <div v-if="item.switchStatus" class="circle" style="width: 10px;height: 10px; border-radius: 50%;background-color: greenyellow;"></div>
                <div v-else class="circle" style="width: 10px;height: 10px; border-radius: 50%;background-color: #999;"></div>
              </div>
            </div>
          </div> -->
        </div>
        <forms ref='forms' :timers="timers" :devid="devid" :obj="obj" :device="device" @closetime ='closetime' @refreshdev="refreshdev"></forms>
        <!-- :menuArr="menuArr"  @refreshRole="refreshRole" -->
      </el-main>
    </el-container>
  </div>
</template>

<script>
import {
  addloopname,
  getdevid,
  setdevdetail,
  getTimes,
  setTimes,
  setcontrol,
  getdevlist,
  getcontrollist,
} from "@/request/api";
import { successmsg, failmsg } from "../../tools/tools";

import forms from "./components/form.vue";
import axios from "axios";
import { stringify } from "qs";


export default {
  components: {
    forms
  },
  data() {
    return {
      switchStatus:'0000000000000000',
      scdevobj:{},
      cabinetName:'',//名称
      cabinetType:'',//类型
      resiveshow:false,
      conline:'',//集控器状态
      value1: '00:00:00',
      value2: '00:00:00',
      concode:'',
      timers:'',
      devid: '',
      conlists: [],
      obj: {
        isshow: false
      },
      devlist: [],
      value: "",
      userinfo: {}, //用户信息
      i: false,
      socket: null,
      device: {}
    };
  },
  created() { },
  mounted() {
    // 获取集控器列表
    this.getconlist();
    // this.getdevlist();
    // 获取设备数据
    // this.timer = setInterval(() => {
    //   this.getdevlist(this.concode);
    // }, 30000);

    this.getDeviceList()
  },
  // beforeRouteLeave(to, from, next) {
  //   next();
  //   if (this.timer) {
  //     clearInterval(this.timer);
  //     this.timer = null;
  //   }
  // },

  methods: {
     // 新增回路名字
    //  addloop(id){
    //         addloopname({ id: 10,
    //             deleteFlag: 10,
    //             name: "111",
    //             loopNumber: "111",
    //             deviceId:id}).then(d=>{
    //             // console.log(d,id);
    //         })
    //     },
    // 修改
    revisename(){
      this.scdevobj.switchStatus = this.switchStatus
        this.scdevobj.cabinetName =this.cabinetName
       this.scdevobj.type =this.cabinetType 
      setdevdetail(this.scdevobj).then(d=>{
        this.getconlist();
        this.getDeviceList()
        successmsg(d.message)
        this.resiveshow = false
      })
    },
    // 取消
    cancleshow(){
      this.resiveshow = false
    },
    revise(num){
      this.resiveshow = true
      getdevid({id:num}).then(d=>{
                if(d.code == '0000'){
                    this.scdevobj = d.data
                    this.cabinetName = d.data.cabinetName
                    this.cabinetType = d.data.type
                }
            })
    },
    // 获取时间
    getTime(){
      if(!this.concode){
        this.concode = this.conlists[0].code
        this.conline = this.conlists[0].onlineStatus
      }
      getTimes({code:this.concode}).then(d=>{
        if(d.code == '0000'){
          this.value1 = d.data.openTime
          this.value2 = d.data.closeTime
        }
      })
    },
    // 时间
    setTime(){
      let t1 =''
      let t2 =''
      if(this.value1){
        t1 = this.value1
      }
      if(this.value2){
        t2 = this.value2
      }
      if(!this.concode){
        this.concode = this.conlists[0].code
        this.conline = this.conlists[0].onlineStatus
      }
      setTimes({
        code: this.concode,
        openTime: t1,
        closeTime: t2
      }).then(d=>{
        if(d.code == '0000'){
          successmsg(d.message)
          this.getTime()
        }
       
      })
     
    },
    newDate(time) {
    var date = new Date(time)
    // var y = date.getFullYear()
    // var m = date.getMonth() + 1
    // m = m < 10 ? '0' + m : m
    // var d = date.getDate()
    // d = d < 10 ? '0' + d : d
    var h = date.getHours()
    h = h < 10 ? '0' + h : h
    var minute = date.getMinutes()
    minute = minute < 10 ? '0' + minute : minute
    var s = date.getSeconds()
    s = s < 10 ? '0' + s : s
    //  y + '-' + m + '-' + d + ' ' +
    return h + ':' + minute + ':' + s
},
    // 刷新
    refreshdev(){
      this.getdevlist(this.concode);
    },
    // 集控器控制
    conallon(){
      if(!this.concode){
        this.concode = this.conlists[0].code
        this.conline = this.conlists[0].onlineStatus
      }
      setcontrol({"code": this.concode,"switchStatus": true}).then(d=>{
        if(d.code == '0000'){
          setTimeout(()=>{
            this.getdevlist(this.concode)
            successmsg(d.message)
          },4000)
          
        }
      })
    },
    conalloff(){
      if(!this.concode){
        this.concode = this.conlists[0].code
        this.conline = this.conlists[0].onlineStatus
      }
      setcontrol({"code": this.concode,"switchStatus": false}).then(d=>{
        if(d.code == '0000'){
          setTimeout(()=>{
            this.getdevlist(this.concode)
            successmsg(d.message)
          },4000)
        }
      })
    },
    closetime(){
      clearInterval(this.timers)
    },
    // 点列表
    readinfo(num,online) {
      this.conline = online
      // console.log(online);
      this.concode = num
      this.getdevlist(num)
      this.getTime()
    },
    // 获取设备列表
    getdevlist(num) {
      // console.log(!num,'1');
      if (!num) {
        // console.log(this.conlists);
        num = this.conlists[0].code
      }else{
        num = this.concode 
      }
      // console.log(num);
      getdevlist({ "centralizedCode": num }).then(d => {
        if (d.code == '0000') {
          this.devlist = d.data
        }
      })
    },
    getDeviceList() {
      // 创建WebSocket 服务器
      const httpURL = axios.defaults.baseURL;
      const wsURL = httpURL.replace(/^http/, 'ws') + '/websocket';
      this.socket = new WebSocket(wsURL);

      // 监听 WebSocket 接收到消息事件
      this.socket.addEventListener("message", (event) => {
        // 处理接收到的 JSON 数据
        const newData = JSON.parse(event.data);
        this.device = newData;
        // console.log("接收到设备数据：", newData);

        // 遍历 devices 数组
        this.devlist.forEach((cabinet) => {
          const device = cabinet.deviceList.find((d) => d.id === newData.id);

          if (device) {
            // console.log("找到匹配的设备：", device.id);
            // 更新匹配的设备数据
            Object.assign(device, newData);
          }
        });
      });
    },

    // 获取集控器列表
    getconlist() {
      getcontrollist().then(d => {
        if (d.code == '0000') {
          // console.log(d);
          this.conlists = d.data
          this.getdevlist()
          this.getTime()
        }
      })
    },
    open(num) {
      // console.log(num);
      this.devid = num
      this.obj.isshow = true;
      this.$refs.forms.getlist(num);
      // this.timers = setInterval(()=>{
      //   this.$refs.forms.getlist(num);
      // },4000)

      // if(!this.obj.isshow){
      //   clearInterval(timers);
      // }

      // setTimeout(()=>{
      //   clearInterval(timers);
      // },60000)
     
    },
    update() {
      this.isRresh = false;
      this.$nextTick(() => {
        this.devicedata.pageNum = this.pageNum;
        this.i = true;
        this.getdevlist(this.i);
        this.isRresh = true;
        this.loading = false;
      });
    },

    // 刷新数据
    reflshdata() {
      // this.loading = true;
      this.update();
      successmsg('刷新成功')
    },

    // 获取设备数据列表
    // getdevlist(i) {
    //   if (!i) {
    //     this.devicedata.productId = this.ProductList[0].productId;
    //   }
    //   Devicelist(this.devicedata)
    //     .then(d => {
    //       if (d.code == "0000") {
    //         // 设备数据
    //         this.lamplist = d.data.records;
    //         this.deviceTypebtn = d.data.records[0].deviceType
    //         // 总页数
    //         this.total = Number(d.data.totalNum);
    //       }
    //       // else {
    //       //   failmsg(d.message);
    //       this.loading = false;
    //       // }
    //     })
    //     .catch(e => {
    //       console.log("设备数据列表接口调用失败");
    //     });
    //   this.loading = false;
    // },
  },

  beforeDestroy() {
    // 在组件销毁前关闭 WebSocket 连接
    this.socket.close();
  },
};
</script>

<style scoped>
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 100%;
  border: none;
}
.notonline {
  color: #333;
}

.online {
  color: greenyellow;
}

/* .devrow{
  background: var(--bg-color)!important;

} */
/* 内容部分 */
.mainbox {
  background-color:#0b1339;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  /* align-items: baseline; */
  justify-content: left;
}

/* 集控器 */
.mainbox .devbox {
  /* background: url("../../assets/image/dev.jpg"); */
  /* background-size: 300px 200px; */
  font-size: 14px;
  width: 240px;
  height: 150px;
 
  border: solid 2px var(--text-color);
  margin: 10px;
  background: #999;
  border-radius: 6px;
}

/* 底部组件 */
/* 全部调光 */
.block {
  height: 40px;
  width: 300px;
  display: inline-block;
  margin-left: 30px;
  margin-top: 100px;
}

.footer div {
  margin-top: 20px;
  font-size: 14px;
}

/* 遮罩层 */

.mask {
  z-index: 2;
  background-color: rgba(0, 0, 0, 0);
  /* 使用固定定位让元素撑满全屏 */
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

.progress-2 {
  z-index: 2;
  position: absolute;
  left: 58vw;
  top: 40vh;
  width: 120px;
  height: 20px;
  border-radius: 20px;
  background: linear-gradient(skyblue 0 0) 0/0% no-repeat lightblue;
  animation: p2 2s infinite steps(10);
}

@keyframes p2 {
  100% {
    background-size: 110%;
  }
}

/* 加载中 */
.loading {
  position: absolute;
  left: 55vw;
  top: 40vh;
  width: 140px;
  height: 20px;
  z-index: 1;
  border: #999 solid 1px;
}

/* 进度条 */
.el-table .el-progress-bar .el-progress-bar__inner {
  border-radius: inherit !important;
}

/* 景区列表宽度 */
.el-row .el-col {
  width: 200px;
  background: var(--bg-color)!important;
  
}

/* 按钮列表 */
.rowlist {
  overflow: auto;
  display: flex;
  align-items: center;
}

.rowlist li {
  margin: 5px;
  width: 80px;
}

.rowlist el-input {
  width: 80px;
}

/* 两个确认按钮 */
.rowlist li:nth-child(7),
li:nth-child(10) {
  width: 65px;
}

.rowlist li p {
  width: 60px;
  font-size: 14px;
}

/* 两个调光的输入框 */
.el-main .el-input {
  margin-right: 10px;
}

/* 导航栏宽度 */
.el-submenu .el-menu-item {
  width: 200px;
}

/* 移入变色 */
.el-submenu .el-menu-item:hover {
  background: skyblue !important;
  color: #fff !important;
}

/* 与主导航栏距离 */
.el-container {
  margin-left: -20px;
  padding: 0;
}

.el-aside {
  width: 209px;
  background-color: #fff;
  text-align: left;
  height: calc(100vh - 130px);
  border-right: #999 solid 1px;
}

.el-main {
  height: calc(100vh - 130px);
  background: #0b1339;

  /* background-color: #fff; */
  color: #333;
}</style>
